public class Ex22 {
    // public static void main(String[] args) {
    //     TicketSeller seller = new TicketSeller();
    //     Thread window1 = new Thread(seller::sellTicket, "窗口1");
    //     Thread window2 = new Thread(seller::sellTicket, "窗口2");

    //     window1.start();
    //     window2.start();
    // }

    // 有100份礼品,两人同时发送，当剩下的礼品小于10份的时候则不再送出。
    // 利用多线程模拟该过程并将线程的名字和礼物的剩余数量打印出来
    // public static void main(String[] args) {
    //     GiftSender sender = new GiftSender();
    //     Thread person1 = new Thread(sender::sendGift, "人1");
    //     Thread person2 = new Thread(sender::sendGift, "人2");

    //     person1.start();
    //     person2.start();
    // }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new OddNumberPrinter(), "线程1");
        Thread thread2 = new Thread(new OddNumberPrinter(), "线程2");

        thread1.start();
        thread2.start();
    }
}


class TicketSeller {
    private int tickets = 1000;

    public synchronized void sellTicket() {
        try {
            Thread.sleep(3000); // 模拟每次领取的时间
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (tickets > 0) {
            System.out.println(Thread.currentThread().getName() + " 卖出了票，剩余： " + --tickets);
        } else {
            System.out.println(Thread.currentThread().getName() + " 没有票了！");
        }
    }
}

class GiftSender {
    private int gifts = 100;

    public synchronized void sendGift() {
        while (gifts > 0) {
            try {
                Thread.sleep(100); // 模拟发送礼品的时间
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (gifts > 0 && gifts >= 10) {
                System.out.println(Thread.currentThread().getName() + " 发送了礼品，剩余： " + --gifts);
            } else {
                System.out.println(Thread.currentThread().getName() + " 停止发送，剩余： " + gifts);
                break;
            }
        }
    }
}

class OddNumberPrinter implements Runnable {
    private static int number = 1;
    private static final Object lock = new Object();

    @Override
    public void run() {
        while (true) {
            synchronized (lock) {
                if (number > 100) {
                    break;
                }
                int currentNumber = number++;
                if (currentNumber % 2 != 0) {
                    System.out.println(Thread.currentThread().getName() + " 输出奇数： " + currentNumber);
                }
                lock.notifyAll();
            }
            try {
                Thread.sleep(10); // 让出CPU时间片
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}